// pages/index/index.js
const TRADIS = require('../../tradis/tradis.js');
import config from '../../utils/config.js';
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    BHeight: 0,
    pageIn: 'index',
    list:[],
    userInfo:{},
    isfb:false,
    isgz:false,
    fbAnimate:false,
    isfz:false,
    hbshow:false,
    winindex:0,
    winTimer:{},
    countdown:'',
    countdownTimer:{},
    SDKVersion:0,
    shareid:'',
    shareHB:{},
    shareType:'',
    isFirst:true,
    isHBgl:false,
    cardid:'',
    nocard:false,
    isCardFirst:false,
    isthird:false,
  
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //定第三方打开时发送log记录
    if (options.xsl_channel!=undefined){
      console.log('定第三方打开时发送log记录');
      wx.reportAnalytics('where', {
        from: options.xsl_channel,
      });
    }
    if (options.from_detail != undefined){
      this.setData({
        isFirst: false,
      })
    }
    wx.getSystemInfo({
      success:(res)=> {
        console.log(res.SDKVersion);
        this.setData({
          SDKVersion: parseInt(res.SDKVersion.toString().replace(/\./g,'')),
        })
      }
    }) 
    if (options.shareid != undefined ) {  
      this.setData({
        shareid: options.shareid
      })
    }
    if (options.cardid != undefined) {
      this.setData({
        cardid: options.cardid
      })
    }
    wx.showShareMenu({
      withShareTicket: true
    })
    // wx.hideShareMenu({
      
    // })


    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    wx.checkSession({
      success: function () {
        console.log('session_key 未过期，并且在本生命周期一直有效');
      },
      fail: function () {
        console.log('session_key 已经失效，需要重新执行登录流程');
        app.getSession() //重新登录
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    TRADIS.tradis(this);
    let token = wx.getStorageSync('token');
    if (token) {
      this.getUserinfo();
      this.fetchRank();
      if (this.data.shareid != ''&&this.data.cardid == '' ){
        this.fetchHB();
      }
    } else {
       wx.navigateTo({
         url: '/pages/auth/getuserinfo',
       })
    }



  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    clearInterval(this.data.winTimer);
    clearInterval(this.data.countdownTimer);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {
  //   var title="";
  //   var path = 'pages/index/index';
  //   var imageUrl="";
  //   if (!this.data.hbshow){
  //     title = '[' + this.data.userInfo.user.nickname + '@我]这个成语真不会，快来看看';
  //     path='pages/index/index?cardid='+wx.getStorageSync('token')+new Date().getTime();
  //     imageUrl = app.getShareTZIMG();
  //   }
  //   else if (this.data.hbshow){
  //     title = this.data.userInfo.user.nickname + '给你发红包了';
  //     path = 'pages/index/index?shareid=' + this.data.userInfo.unopened_bouns.id;
  //     imageUrl = app.getShareHBIMG();
  //   }
  //   return {
  //     title: title,
  //     imageUrl: imageUrl,
  //     path: path,
  //     success: (res)=> {
  //       if (!this.data.hbshow) {
  //         wx.showToast({
  //           title: '赠送成功',
  //           icon: 'none',
  //         }) 

  //       }
  //       else{
  //         this.setData({
  //           hbshow:false,
  //           isHBgl:true,
  //           isFirst:false,
  //         });
  //         wx.showToast({
  //           title: '分享成功',
  //           icon: 'none',
  //         }) 
  //       }
       
  //     },
  //     fail: function (res) {
  //       // 转发失败
  //       wx.showToast({
  //         title: '分享失败',
  //         icon: 'none',
  //       })
  //     }
      
  //   }
  
  // },
  onShareAppMessage:function(){
    var shareObj = app.getShareDefault();
    return {
      title:  shareObj.sharetxt,
      // imageUrl:'../../images/sharedefault3.png',
       imageUrl: shareObj.imgurl,
      path: '/pages/index/index',
      success: (res) => {
        if (res.shareTickets != undefined) {
          wx.reportAnalytics('isgroup', {
            hasgid: 'have',
          });
          wx.getShareInfo({
            shareTicket: res.shareTickets[0],
            success: (response) => {
              wx.request({
                url: app.globalData.api + '/share/sharegold.html&token='+wx.getStorageSync('token'),
                method:'post',
                data:{
                  "encryptedData": response.encryptedData,
                  "iv": response.iv,
                },
                success:(res2)=>{
                  wx.showToast({
                    title: res2.data.data.msg,
                    icon:'none'
                  })
                }
              })

            }
          })
        }
        else {
          wx.reportAnalytics('isgroup', {
            hasgid: 'no',
          });

        }
        // wx.showToast({
        //   title: '分享成功',
        //   icon: 'none',
        // }) 
      },
      fail: function (res) {
        // 转发失败
        wx.showToast({
          title: '分享失败',
          icon: 'none',
        })
      }

    }
  },
  closeHBgl:function(){
    this.setData({
      isHBgl: false,
    });
  },
  gamestart:function(e){
    this.setData({
      isHBgl: false,
    });
    let token = wx.getStorageSync('token');
    if (token) {
      console.log(e.detail.formId);
      var _this = this;
      if (this.data.userInfo.gold >= this.data.userInfo.single_gold || this.data.userInfo.dare_num>0) {
        wx.request({
          url: app.globalData.api + '/Users/formId.html&token=' + wx.getStorageSync('token') + '&formId=' + e.detail.formId,
          header: {
            v: 2,
          },
          success: function (res) {
          }
        });
        wx.navigateTo({
          url: '/pages/game/play',
        })

      }
      else {
        // wx.showToast({
        //   title: '挑战卡不足',
        //   icon:'none',
        // })
        // wx.showModal({
        //   title: '提醒',
        //   content: '没有挑战卡了，邀请好友免费赠送一张吧',
        //   showCancel:false,
        // })
        this.setData({
          nocard:true,
        })
      }
    } else {
      wx.navigateTo({
        url: '/pages/auth/getuserinfo',
      })
    } 

    
  },
  thridStart:function(){
    wx.navigateToMiniProgram({
      appId: 'wx5ccf73a5edb50795',
      path: this.data.userInfo.third.query + '%7cxsl_from%3d' + config.Appid + '%7cxsl_position%3d' + config.shortName
    })
  },
  closeTips:function(){
    this.setData({
      nocard: false,
    })
  },
  toplay:function(){
    this.setData({
      hbshow: false,
    })
    wx.navigateTo({
      url: '/pages/game/play',
    })
    // if (this.data.userInfo.dare_num > 0) {
    //   wx.navigateTo({
    //     url: '/pages/game/play',
    //   })
    // }
    // else {
    //   wx.showModal({
    //     title: '提醒',
    //     content: '没有挑战卡了，邀请好友免费赠送一张吧',
    //     showCancel: false,
    //   })
    // }
  },
  hbclose:function(){
    this.setData({
      hbshow:false,
      isFirst: false,
      isHBgl: false,
    })
  },
  // Play:function(){
  //   this.setData({
  //     isfb: false,
  //   })
  //   wx.navigateTo({
  //         url: '/pages/game/play',
  //   })
  // },
  click_count(e) {
    var url = 'https://r.d1fm.com/r.gif?appid=' + e.currentTarget.dataset.appid + '&path=' + encodeURIComponent(e.currentTarget.dataset.path) + '&openid=' + wx.getStorageSync('openid') + '&action=click&xsl_from=caichengyudaquan&xsl_position=' + e.currentTarget.dataset.position;
    console.log(url);
    wx.request({
      url: url
    })
  },
  openGame:function(e){
    wx.navigateToMiniProgram({
      appId: e.currentTarget.dataset.appid,
      path: e.currentTarget.dataset.path,
      success: (res) => {
        this.click_count(e);
      }
    })
  },
  openPH:function(){
    wx.navigateTo({
      url: '/pages/game/rank',
    })
  },
  openGC: function () {
    wx.navigateTo({
      url: '/pages/user/index',
    })
  },
  close: function () {
    this.setData({
      isfb: false,
    })
  },
  fetchHB:function(){
    wx.request({
      method:'post',
      url: app.globalData.api + '/open/index.html&token=' + wx.getStorageSync('token'),
      data:{
        "bouns_id": this.data.shareid
      },
      success: (res) => {
        if(res.data.code==0){
          this.setData({
            shareHB: res.data.data,
            hbshow:true,
          });
          if (this.data.cardid!=''){
            this.setData({
              hbshow: false,
            })
          }
        }
      }
    })
  },
  fetchCard: function () {
    wx.request({
      method: 'post',
      url: app.globalData.api + '/darecard/index.html&token=' + wx.getStorageSync('token'),
      data: {
        "sharekey": this.data.cardid
      },
      success: (res) => {
        if (res.data.code == 0) {
          if (res.data.data.add_dare>0){
            this.data.userInfo.dare_num = this.data.userInfo.dare_num + parseInt(res.data.data.add_dare);
            this.setData({
              userInfo: this.data.userInfo,
            })
            wx.showToast({
              title: '挑战卡领取成功',
            })
          }
          else{
            wx.showToast({
              title: '该挑战卡已领取',
              icon:'none',
            })
          }
        }
        else{
          this.fetchError(res.data.code);
        }
      }
    })
  },
  getUserinfo:function(){
    wx.request({
      url: app.globalData.api +'/home/index.html&token='+wx.getStorageSync('token'),
      success:(res)=>{
        if(res.data.code==0){
          this.setData({
            userInfo:res.data.data,
          });
          wx.setStorageSync('ad', res.data.data.ad);
          if (res.data.data.third.is_open==1){
            this.setData({
              isthird:true,
            })
          }
          if (this.data.userInfo.unopened_bouns.id != undefined && this.data.isFirst){
            this.setData({
              hbshow:true,
            })
            if (this.data.cardid != '') {
              this.setData({
                hbshow: false,
              })
            }
          }
          var i=0;
          this.data.winTimer=setInterval(()=>{
            i++;
            this.setData({
              winindex:i%10,
            })

          },3000);
          if (this.data.userInfo.countdown>0){
            this.data.countdownTimer = setInterval(() => {
              if (this.data.userInfo.countdown <= 0) {
                clearInterval(this.data.countdownTimer);
                this.data.userInfo.dare_num++;

              }
              this.data.userInfo.countdown--;
              var s = this.integer_ten(parseInt(this.data.userInfo.countdown % 60));
              var m = this.integer_ten(parseInt(this.data.userInfo.countdown / 60));
              var h = this.integer_ten(parseInt(this.data.userInfo.countdown / 3600));
              this.data.countdown = h + ':' + m + ':' + s;
              this.setData({
                userInfo: this.data.userInfo,
                countdown: this.data.countdown,
              })

            }, 1000)

          }
          if (this.data.cardid != '') {
            this.fetchCard();
          }

        }
        else{
          this.fetchError(res.data.code);
        }
      }
    })
  },
  fetchRank: function () {
    wx.request({
      url: app.globalData.api + 'ranking/goldrank.html&token=' + wx.getStorageSync('token'),
      method: 'get',
      success: (res) => {
        if (res.data.code == 0) {
          wx.hideLoading();
          this.setData({
            list: res.data.data
          })
        }
        else {
          this.fetchError(res.data.code);
        }
      }
    })
  },
  integer_ten:function(num){
    if(num<10){
      return '0'+num;
    }
    else{
      return num;
    }

  },
  showGZ:function(){
      this.setData({
        isgz:true,
      })
  },
  closeGZ:function(){
    this.setData({
      isgz: false,
    })
  },
  open_hb:function(){
      this.setData({
        isfz:true,
      });
      setTimeout(()=>{
        wx.navigateTo({
          url: '/pages/hongbao/detail?fee=' + this.data.shareHB.fee,
        })
      },1500)
  },
  open_hb_self:function(){
    this.setData({
      isfz: true,
    });
    setTimeout(() => {
      wx.navigateTo({
        url: '/pages/hongbao/detail?fee=' + this.data.userInfo.unopened_bouns.fee,
      })
    }, 1500)
  },
  fetchError: function (code) {
    if (code == 40001) {
      wx.navigateTo({
        url: '/pages/auth/getuserinfo',
      })
    }
    else if (code == 73000) {
      wx.showToast({
        title: '挑战卡无效',
        icon:'none',
      })
    }
    else if (code == 73002) {
      wx.showToast({
        title: '无法领取自己的挑战卡',
        icon: 'none',
      })
    }
    else if (code == 73004) {
      if (this.data.isCardFirst){
        return false;
      }
      wx.showModal({
        title: '提示',
        content: '您今天已领取过该好友赠送的挑战卡,请明天再领取',
        showCancel:false,
        success:()=>{
          this.setData({
            isCardFirst:true,
          })
        }
      })
    }


  }
})